<template>
  <view class="following-page">
    <!-- 顶部导航 -->
    <view class="page-header">
      <view class="nav-back" @click="goBack">
        <text class="iconfont">⬅️</text>
      </view>
      <text class="page-title">我的关注</text>
      <view class="nav-placeholder"></view>
    </view>
    
    <!-- 内容区域 -->
    <scroll-view class="content" scroll-y @scrolltolower="loadMore" refresher-enabled @refresherrefresh="refreshList" :refresher-triggered="refreshing">
      <!-- 空状态 -->
      <view v-if="followingList.length === 0 && !loading" class="empty-state">
        <text class="empty-icon">👥</text>
        <text class="empty-text">您还没有关注任何人</text>
        <view class="discover-btn" @click="goToDiscover">去发现</view>
      </view>
      
      <!-- 加载状态 -->
      <view v-if="loading && !refreshing" class="loading-state">
        <view class="loading-content">
          <text class="loading-icon">🔄</text>
          <text class="loading-text">加载中...</text>
        </view>
      </view>
      
      <!-- 关注列表 -->
      <view v-if="followingList.length > 0" class="following-list">
        <view 
          v-for="(item, index) in followingList" 
          :key="item.id" 
          class="following-item"
        >
          <view class="user-info" @click="goToUserDetail(item.id)">
            <image class="avatar" :src="item.avatar" mode="aspectFill"></image>
            <view class="info-detail">
              <text class="nickname">{{item.nickname}}</text>
              <text class="bio">{{item.bio || '这个人很懒，什么都没写~'}}</text>
            </view>
          </view>
          
          <view class="action-btn">
            <button class="unfollow-btn" @click="handleUnfollow(item, index)">取消关注</button>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view v-if="hasMoreData && followingList.length > 0" class="load-more">
        <text class="load-more-text">加载更多...</text>
      </view>
      
      <!-- 无更多数据 -->
      <view v-if="!hasMoreData && followingList.length > 0" class="no-more">
        <text class="no-more-text">没有更多数据了</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getFollowingList, unfollowUser } from '@/api/follow'

// 响应式数据
const followingList = ref([])
const loading = ref(false)
const refreshing = ref(false)
const hasMoreData = ref(true)
const userIdParam = ref('')
const currentUser = ref(null)
const followingParams = ref({
  page: 0,
  size: 10
})

// 初始化
onMounted(() => {
  // 获取URL参数
  const pages = getCurrentPages()
  const page = pages[pages.length - 1]
  const query = page.options
  userIdParam.value = query.userId || ''
  
  // 获取当前登录用户信息
  try {
    const userInfo = uni.getStorageSync('userInfo')
    if (userInfo) {
      currentUser.value = userInfo
    }
  } catch (err) {
    console.error('获取用户信息失败:', err)
  }
  
  // 加载关注列表
  fetchFollowingList()
})

// 获取关注列表
const fetchFollowingList = async (loadMore = false) => {
  if (loading.value) return
  if (!userIdParam.value) return
  
  loading.value = true
  
  try {
    const res = await getFollowingList(userIdParam.value, followingParams.value)
    
    if (res.code === 200) {
      if (loadMore) {
        followingList.value = [...followingList.value, ...res.data]
      } else {
        followingList.value = res.data
      }
      
      // 判断是否还有更多数据
      hasMoreData.value = !res.data.last
      
      console.log('关注列表加载成功:', res.data)
    } else {
      uni.showToast({
        title: res.message || '获取关注列表失败',
        icon: 'none'
      })
    }
  } catch (err) {
    console.error('获取关注列表出错:', err)
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 刷新列表
const refreshList = () => {
  refreshing.value = true
  followingParams.value.page = 0
  fetchFollowingList()
}

// 加载更多
const loadMore = () => {
  if (!hasMoreData.value || loading.value) return
  
  followingParams.value.page++
  fetchFollowingList(true)
}

// 取消关注
const handleUnfollow = async (user, index) => {
  if (!user || !user.id) return
  
  uni.showModal({
    title: '提示',
    content: `确定要取消关注 ${user.nickname} 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const response = await unfollowUser(user.id)
          
          if (response.code === 200) {
            // 从列表中移除
            followingList.value.splice(index, 1)
            
            uni.showToast({
              title: '已取消关注',
              icon: 'success'
            })
          } else {
            uni.showToast({
              title: response.message || '取消关注失败',
              icon: 'none'
            })
          }
        } catch (err) {
          console.error('取消关注失败:', err)
          uni.showToast({
            title: '操作失败，请稍后重试',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 前往用户详情页
const goToUserDetail = (userId) => {
  if (userId === currentUser.value?.id) {
    // 如果是当前用户，跳转到个人中心
    uni.switchTab({
      url: '/pages/usercenter/index'
    })
  } else {
    // 如果是其他用户，跳转到用户详情页
    uni.navigateTo({
      url: `/pages/discovery/user-detail?userId=${userId}`
    })
  }
}

// 前往发现页
const goToDiscover = () => {
  uni.switchTab({
    url: '/pages/discovery/index'
  })
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}
</script>

<style>
.following-page {
  min-height: 100vh;
  background-color: #f8f9fa;
  position: relative;
}

.page-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 88rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  z-index: 100;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.nav-back {
  padding: 10rpx;
}

.page-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.nav-placeholder {
  width: 40rpx;
}

.content {
  margin-top: 88rpx;
  height: calc(100vh - 88rpx);
  padding: 20rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.empty-icon {
  font-size: 100rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.discover-btn {
  background-color: #3498db;
  color: white;
  font-size: 28rpx;
  padding: 16rpx 60rpx;
  border-radius: 40rpx;
}

.loading-state {
  padding: 40rpx 0;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.loading-icon {
  font-size: 40rpx;
  margin-bottom: 20rpx;
  animation: rotate 1s linear infinite;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

.following-list {
  padding: 0 10rpx;
}

.following-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.user-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.info-detail {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.nickname {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 8rpx;
}

.bio {
  font-size: 24rpx;
  color: #999;
  max-width: 400rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.action-btn {
  margin-left: 20rpx;
}

.unfollow-btn {
  font-size: 24rpx;
  padding: 10rpx 20rpx;
  background-color: #f0f0f0;
  color: #666;
  border-radius: 30rpx;
  border: none;
  line-height: 1.5;
  min-width: 140rpx;
}

.load-more, .no-more {
  text-align: center;
  padding: 30rpx 0;
}

.load-more-text, .no-more-text {
  font-size: 24rpx;
  color: #999;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style> 